import React from 'react';
import { Icon } from 'antd';
import { WeaLocaleProvider, WeaProgress } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;
import { isEmpty } from 'lodash';
import { ELEMENT_TYPES } from '../constants/ActionTypes';
import objectAssign from 'object-assign';

const {
  RSS,
  NEWS,
  WORKFLOW,
  CUSTOMPAGE,
  REPORTFORM,
  OUTDATA,
  FORMMODECUSTOMSEARCH,
  ADDWF,
  // TASK,
  BLOGSTATUS,
  CONTACTS,
  UNREAD_DOCS,
  MESSAGE_REMINDING,
  MY_PROJECTS,
  NEW_CUSTOMERS,
  NEW_MEETING,
  UNREAD_COOPERATION,
  // MONTH_TARGET,
  DAY_PLAN,
  // SUBSCRIBE_KONWLEDG,
  MORE_NEWS,
  MAGAZINE,
  STOCK,
  DOC_CONTENT,
  AUDIO,
  FAVOURITE,
  FLASH,
  PICTURE,
  MYCALENDAR,
  IMGSLIDE,
  NEWNOTICE,
  OUTTERSYS,
  SCRATCHPAD,
  WEATHER,
  VIDEO,
  SLIDE,
  DATACENTER,
  JOBSINFO,
  SEARCHENGINE,
  // NOTICE,
  // PLAN,
  CUSTOMMENU,
  WORKTASK,
  MAIL,
  MEETINGCALENDAR,
  LOGIN_NEWS,
  MYTASK,
  NEW_DY,
  QUICKEENTRY,
  RANKINGLIST,
  TIMELINE,
} = ELEMENT_TYPES;
// 判断元素是否为E9改造后的元素
const isE9Element = (ebaseid) => {
    for (let key in ELEMENT_TYPES) {
        if (ebaseid === ELEMENT_TYPES[key]) return true;
    }
    return false;
};

// 无权访问的元素的组件
class NoRightCom extends React.Component {
    render() {
        return (
            <div style={{ width: '100%', height: '50px', lineHeight: '50px', textAlign: 'center' }}>
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@04v1zq`} type="exclamation-circle" style={{ marginRight: '8px', color: '#fa0' }} /><span>{getLabel(2012, '对不起，您暂时没有权限！')}</span>
            </div>
        );
    }
}

// 处理计算E9元素高度
const handleHeight = (oldstyle) => {
    let style = {};
    if (!isEmpty(oldstyle)) {
        style = { ...oldstyle };
        if (style.height) {
            const height = style.height.replace('px', '');
            let nherght = parseInt((parseInt(height) - 32 + 1) / 25) * 31 + 32;
            style.height = `${nherght}px`;
        }
    }
    return style;
};

// 返回前一个tab
const doPrev = (eid) => {
    $(`#tabContainer_${eid}`).scrollTo({ top: '0px', left: (`${$(`#tabContainer_${eid}`).get(0).scrollLeft - 77}px`) }, 500);
};

// 进入下一个tab
const doNext = (eid) => {
    $(`#tabContainer_${eid}`).scrollTo({ top: '0px', left: (`${$(`#tabContainer_${eid}`).get(0).scrollLeft + 77}px`) }, 500);
};

// 处理多tab的宽度，并判断是否显示左右箭头导航
const handleWidth = (eid, hpid, length, canHeadbar, displayPosition) => {
    let divWidth = length * 77 + 36;
    let hpWidth = $(`#content_${eid}`).width();
    if (parseInt(hpid) < 0) {
        // let hpdom = $("#item_"+eid).parents("div[class='homepage']")[0];
        let hpdom = $(`#item_${eid}`).parents('div.homepage')[0];
        hpWidth = $(hpdom).parent().width();
        hpWidth -= 20;
        divWidth -= 36;
    }
    // let titleWidth = hpWidth - 10;
    if (!canHeadbar) {
        hpWidth -= $(`#content_${eid}`).find('.optoolbar').width();
    }
    if (parseFloat(divWidth) > parseFloat(hpWidth)) {
        $(`#tabnavprev_${eid}`).css('display', 'block');
        $(`#tabnavnext_${eid}`).css('display', 'block');
        if (length > 1) {
            if (!canHeadbar) {
                let width = $(`#content_${eid}`).find('.optoolbar').width() + 5;
                $(`#tabContainer_${eid}`).css('width', hpWidth - 55);
                $(`#tabnavnext_${eid}`).css('right', `${width}px`);
            } else {
                $(`#tabContainer_${eid}`).css('width', hpWidth - 55);
                if (displayPosition && displayPosition == 'bottom') {
                    $(`#titleContainer_${eid}`).css('width', hpWidth);
                }
            }
            $(`#tabContainer_${eid}`).css('display', '');
            $(`#tabContainer_${eid}`).css('margin-left', '0px');
            $(`#tabContainer_${eid}`).css('margin-right', '0px');
        } else {
            $(`#tabnavprev_${eid}`).css('display', 'none');
            $(`#tabnavnext_${eid}`).css('display', 'none');
            $(`#tabContainer_${eid}`).css('display', 'none');
        }
    } else {
        $(`#tabnavprev_${eid}`).css('display', 'none');
        $(`#tabnavnext_${eid}`).css('display', 'none');
        if (length > 1) {
            if (!canHeadbar) {
                $(`#tabContainer_${eid}`).css('width', hpWidth - 50);
            } else {
                $(`#tabContainer_${eid}`).css('width', hpWidth);
            }
            $(`#tabContainer_${eid}`).css('display', '');
            $(`#tabContainer_${eid}`).css('margin-left', '0');
            $(`#tabContainer_${eid}`).css('margin-right', '0');
        } else {
            $(`#tabContainer_${eid}`).css('display', 'none');
        }
    }
    $(`#tabContainer_${eid} table`).css('min-width', length * 77);
};


const openLinkUrl = function (url, linkmode, obj = {}) {
    if (!url) return;
    if (linkmode == '1') { // 当前页打开
        if (window.doThemeAction) {
            window.doThemeAction('onLoadMain', { url });
        } else {
            window.location.href = url;
        }
    } else if (obj && obj > 0) { // 弹出页打开
        window.open(url, '_blank');
    } else {
        const opebObj = window.open(url, '_blank') || {};
        if (obj.ebaseid == '6') {
            const loop1 = setInterval(() => {
                clearInterval(loop1);
                setTimeout(() => {
                    try {
                        if (obj.eid) {
                            window.element_unReadDoc_reLoad(obj.eid);
                        }
                    } catch (e) {
                    }
                }, 500);
            }, 1000);
        }
        if (obj.ebaseid == '13') {
            const loop1 = setInterval(() => {
                clearInterval(loop1);
                setTimeout(() => {
                    try {
                        if (obj.eid) {
                            window.element_cooperation_reLoad(obj.eid);
                        }
                    } catch (e) {
                    }
                }, 500);
            }, 1000);
        }
        if (obj.ebaseid == '16') {
            const loop1 = setInterval(() => {
                clearInterval(loop1);
                setTimeout(() => {
                    try {
                        if (obj.eid) {
                            window.element_mail_reLoad(obj.eid);
                        }
                    } catch (e) {
                    }
                }, 500);
            }, 1000);
        }
        const loop = setInterval(() => {
            if (opebObj.closed) {
                clearInterval(loop);
                setTimeout(() => {
                    try {
                        // obj.ebaseid == '7' || obj.ebaseid == '7_DY' && window.element_news_reLoad();
                        if ((obj.ebaseid == '7' || obj.ebaseid == '7_DY') && obj.eid && window.element_workflow_reLoad) {
                            // // 去掉未读标识
                            // $(`#${obj.id}`).find("img.wfremindimg").remove();
                            // //去掉提醒方式样式
                            // $(`#${obj.id}`).find("a font").removeAttr('style');
                            window.element_news_reLoad(obj.eid);
                        }
                        obj.ebaseid == '8' && window.element_workflow_reLoad();
                    } catch (e) {

                    }
                }, 500);
            }
        }, 1000);
    }
};

// 加载提醒方式
const loadRemind = (obj, linkmode, isremind, fun, contentfontsize, ebaseid, eid, style, isPageAutoWrap) => {
    if (obj.userid) {
        style = style || {};
        let ahtml = `<a href='javascript:openhrm(${obj.userid});' onclick='pointerXY(event)' title=${obj.name} ><font class='font wea-f${contentfontsize}'>${obj.name}</font></a>`;
        if (obj.usertype && obj.usertype == '1') {
            ahtml = `<a target='_blank' href='/spa/crm/static/index.html#/main/crm/customerView?customerId=${obj.userid}' title=${obj.name}><font class='font wea-f${contentfontsize}'>${obj.name}</font></a>`;
        }
        return <span style={style} dangerouslySetInnerHTML={{ __html: ahtml }} />;
    }

    let pageAutoWrapStyle = {};
    if (isPageAutoWrap && isPageAutoWrap == '1' && (ebaseid == '7' || ebaseid == '8')) {
        pageAutoWrapStyle = {
            whiteSpace: 'normal',
            wordBreak: 'break-all',
            wordWrap: 'break-word',
            display: 'block',
        };
    }
    let nametitle = obj.name;
    if (obj.pretitle) nametitle = obj.pretitle + nametitle;
    if (obj.lasttitle) nametitle += obj.lasttitle;
    if (obj.coworkTitle) nametitle = obj.coworkTitle;
    const showName = <font style={pageAutoWrapStyle} dangerouslySetInnerHTML={{ __html: obj.name }} />;
    let nametitle_new = '';
    if (nametitle) {
        nametitle_new = nametitle.replace(/<\/?[^>]*>/g, ''); // 去除HTML Tag
        nametitle_new = nametitle_new.replace(/[\r\n]/g, ''); // 去除换行
    }
    let lasttitle_new = <font dangerouslySetInnerHTML={{ __html: obj.lasttitle }} />;
    let signNturesIcon = (ebaseid == '8' ? <img onClick={() => fun(obj.requestid,obj.f_weaver_belongto_userid,obj.f_weaver_belongto_usertype)} title={getLabel(386528, '查看流转意见')} data-requestid={obj.requestid || '-1'} className="portal_workflow_signaturesIcon " src="/images/ecology8/homepage/req_wev8.png" width="14px" height="16px" alt="" /> : '');

    let wfremindimgId = `portal_wfremindimg_${obj.requestid}`;
    if (!obj.requestid && obj.link && (ebaseid == '7' || ebaseid == '7_DY')) {
        let index = obj.link.indexOf('&');
        if (index > 0) wfremindimgId = `portal_wfremindimg_news_${obj.link.substring(0, index).replace(/[^0-9]/ig, '')}`;
    }
    if (obj.img) {
        if (isremind) {
            style = style || {};
            let tempremind = '';
            if (isremind.indexOf('#') > -1) {
                tempremind = isremind.substring(0, isremind.indexOf('#') - 1);
            } else {
                tempremind = isremind;
            }
            if (ebaseid == '7') {
                if (obj.img != '/images/BDTop_wev8.gif') {
                    if (tempremind.indexOf('3') !== -1) {
                        let color = isremind.substr(isremind.indexOf('#'));
                        style.color = color;
                    }
                    if (tempremind.indexOf('1') !== -1) {
                        style.fontWeight = 'bold';
                    }
                    if (tempremind.indexOf('2') !== -1) {
                        style.fontStyle = 'italic';
                    }
                }
            } else {
                if (tempremind.indexOf('3') !== -1) {
                    let color = isremind.substr(isremind.indexOf('#'));
                    style.color = color;
                }
                if (tempremind.indexOf('1') !== -1) {
                    style.fontWeight = 'bold';
                }
                if (tempremind.indexOf('2') !== -1) {
                    style.fontStyle = 'italic';
                }
            }
            if (tempremind.indexOf('0') === -1) {
                return <span className="td-span"><a href="javascript:void(0);" onClick={() => openLinkUrl(obj.link, linkmode, { ...obj, ebaseid, eid })} data-link={obj.link} id={obj.requestid} data-requestid={obj.requestid} title={nametitle_new}><font style={{ width: '100%' }} className={`font wea-f${contentfontsize}`}><font style={style}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ? <b style={{ fontWeight: 'bold' }}>{lasttitle_new}</b> : null}</font></font></a>{signNturesIcon}</span>;
            }
                return <span id={wfremindimgId} className="td-span"><a href="javascript:void(0);" onClick={() => openLinkUrl(obj.link, linkmode, { ...obj, ebaseid, id: wfremindimgId, eid })} data-link={obj.link} data-requestid={obj.requestid} title={nametitle_new}><font className={`font wea-f${contentfontsize}`} style={{ width: '100%' }}><font style={style}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ? <b style={{ fontWeight: 'bold' }}>{lasttitle_new}</b> : null}</font></font></a><img className="wfremindimg" src={obj.img} />{signNturesIcon}</span>;
        }

        return (
            <span id={wfremindimgId} className="td-span">
                <a href="javascript:void(0);"
                  onClick={() => openLinkUrl(obj.link, linkmode, { ...obj, ebaseid, id: wfremindimgId, eid })}
                  data-link={obj.link}
                  data-requestid={obj.requestid}
                  title={nametitle_new}
                >
                    <font className={`font wea-f${contentfontsize}`} style={{ width: '100%' }}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ?
                        <b style={{ fontWeight: 'bold' }}>{lasttitle_new}</b> : null}
                    </font>
                </a>
                <img className="wfremindimg" src={obj.img} />{signNturesIcon}
            </span>
        );
    }

    if (style) {
		if (ebaseid == '16') {
            return <span className="td-span"><a href="javascript:void(0);" onClick={() => openLinkUrl(obj.link, linkmode, { ...obj, ebaseid, eid })} data-link={obj.link} id={obj.requestid} data-requestid={obj.requestid} title={nametitle_new}><font style={style} className={`font wea-f${contentfontsize}`}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ? <b style={{ fontWeight: 'bold' }}>{obj.lasttitle}</b> : null}</font></a>{signNturesIcon}</span>;
        }
        return <span className="td-span"><a href="javascript:void(0);" onClick={() => openLinkUrl(obj.link, linkmode, obj.requestid)} data-link={obj.link} id={obj.requestid} data-requestid={obj.requestid} title={nametitle_new}><font style={style} className={`font wea-f${contentfontsize}`}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ? <b style={{ fontWeight: 'bold' }}>{obj.lasttitle}</b> : null}</font></a>{signNturesIcon}</span>;
    }
		return <span className="td-span"><a href="javascript:void(0);" onClick={() => openLinkUrl(obj.link, linkmode, obj.requestid)} data-link={obj.link} id={obj.requestid} data-requestid={obj.requestid} title={nametitle_new}><font className={`font wea-f${contentfontsize}`} style={{ width: '100%' }}>{obj.pretitle ? obj.pretitle : ''}{showName}{obj.lasttitle ? <b style={{ fontWeight: 'bold' }}>{obj.lasttitle}</b> : null}</font></a>{signNturesIcon}</span>;
};

// 处理属性为集合的数据
const loadListName = (contentfontsize, list, linkmode) => {
    if (!list || list.length === 0) return <span />;
    let html = list.map((obj, o) => {
        let dotstr = o === 0 ? '' : ' , ';
        if (obj && typeof obj === 'object' && obj.constructor === Object) {
            if (obj.userid) {
                let ahtml = `<a href='javascript:openhrm(${obj.userid});' onclick='pointerXY(event)' title=${obj.name}><font style='color:#000000;' class='font wea-f${contentfontsize}'>${dotstr}${obj.name}</font></a>`;
                if (obj.usertype && obj.usertype == '1') {
                    ahtml = `<a target='_blank' href='/spa/crm/static/index.html#/main/crm/customerView?customerId=${obj.userid}' title=${obj.name}><font style='color:#000000;' class='font wea-f${contentfontsize}'>${dotstr}${obj.name}</font></a>`;
                }
                return <span dangerouslySetInnerHTML={{ __html: ahtml }} />;
            }
            return <font>{dotstr}<a href="javascript:void(0);" onClick={e => openLinkUrl(obj.link, linkmode, e)} title={obj.name}><font className={`font wea-f${contentfontsize}`}>{obj.name}</font></a></font>;
        } else if (obj && typeof obj === 'object' && obj.constructor === Array) {
            let shtml = obj.map((obj) => {
                if (obj.userid) {
                    let ahtml = `<a href='javascript:openhrm(${obj.userid});' onclick='pointerXY(event)' title=${obj.name}><font style='color:#000000;' class='font wea-f${contentfontsize}'>${dotstr}${obj.name}</font></a>`;
                    if (obj.usertype && obj.usertype == '1') {
                        ahtml = `<a target='_blank' href='/spa/crm/static/index.html#/main/crm/customerView?customerId=${obj.userid}' title=${obj.name}><font style='color:#000000;' class='font wea-f${contentfontsize}'>${dotstr}${obj.name}</font></a>`;
                    }
                    return <span dangerouslySetInnerHTML={{ __html: ahtml }} />;
                }
                return <a href="javascript:void(0);" onClick={e => openLinkUrl(obj.link, linkmode, e)} title={obj.name}><font className={`font wea-f${contentfontsize}`}>{obj.name}</font></a>;
            });
            return <font>{dotstr}{shtml}</font>;
        }
    });
    return <span className="td-span-formmodecustomsearch">{html}</span>;
};

const _isHtml = function (htmlStr) {
    if (!htmlStr) return false;
    let reg = /<[^>]+>/g;
    return reg.test(htmlStr) || htmlStr.indexOf('&') > -1;
};

// 处理antd Table数据，返回columns
const formatData = (obj, esetting, fun) => {
    const { imgSymbol, linkmode, isremind, widths, titles, ebaseid, eid, fontStyle = {}, isPageAutoWrap, dataColoums = [] } = esetting;
    const { contentfontsize = '12' } = fontStyle;
    const columns = new Array();
    let i = 0;
    // 加载行小图标
    if (imgSymbol) {
        const iObj = {
            dataIndex: 'imgSymbol',
            key: 'imgSymbol',
            width: ebaseid == 'FormModeCustomSearch' ? '1%' : '8px',
            render: () => <img style={{ marginBottom: '3px' ,display:'block'}} name="esymbol" src={imgSymbol} />,
        };
        columns.push(iObj);
    }
    let dataColoumsNew = dataColoums;
    if (ebaseid == '7') {
        dataColoumsNew = dataColoums.filter((item) => {
            if (item.id != '11') {
                return item;
            }
        });
    }
    for (let k in obj) {
        if (k !== 'key') {
            let colObj = {};
            const kv = obj[k];
            if (kv && typeof kv === 'object' && kv.constructor === Object) { // 判断属性值的类型，Object类型
                colObj = {
                    dataIndex: k,
                    className: ebaseid === ELEMENT_TYPES.WORKFLOW && k === 'requestname' ? 'reqdetail' : '',
                    key: k,
                    render: text => loadRemind(text, linkmode, isremind, fun, contentfontsize, ebaseid, eid, {}, isPageAutoWrap),
                };
            } else if (kv && typeof kv === 'object' && kv.constructor === Array) { // 判断属性值的类型，List类型，建模查询中心元素用到
                colObj = {
                    dataIndex: k,
                    key: k,
                    render: text => loadListName(contentfontsize, text, linkmode),
                };
            } else { // 判断属性值的类型，字符串类型
                colObj = {
                    dataIndex: k,
                    key: k,
                    render: (text) => {
                        if (typeof text === 'string') {
                            if (_isHtml(text)) { // 判断字符串是否含有html
                                return <font className={text.indexOf("class='font'") == -1 ? `font wea-f${contentfontsize}` : `wea-f${contentfontsize}`} dangerouslySetInnerHTML={{ __html: text }} />;
                            }
                                return <font className={`font wea-f${contentfontsize}`}>{text}</font>;
                        }
                            return <font className={`font wea-f${contentfontsize}`} />;
                    },
                };
            }
            if (k == 'finish') {
                colObj = {
                    dataIndex: 'finish',
                    key: 'finish',
                    render: text => <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@l4qyky`} percent={text} strokeColor="#B37BFA" />,
                };
            }
            if (titles) colObj.title = titles[i];
            if (!isEmpty(dataColoumsNew) && dataColoumsNew[i]) {
                colObj.title = <font className={`font wea-f${contentfontsize}`}>{dataColoumsNew[i].fieldName}</font>;
            }
            let width = colObj.dataIndex && widths[colObj.dataIndex];
            if (ebaseid == 'contacts' && (width < 50 || width === '*')) {
                width = '50px';
            }
            if (widths[colObj.dataIndex] != '' && widths[colObj.dataIndex] != '*') {
                if (width && width.indexOf('%') == -1) {
                    width += 'px';
                }
            }
            if (widths) colObj.width = width;

            columns.push(colObj);
            i += 1;
        }
    }
    return columns;
};


// 获取当前时间戳(以s为单位)
const formatDate = function (_date, format) {
    let date = {
        'M+': _date.getMonth() + 1,
        'd+': _date.getDate(),
        'h+': _date.getHours(),
        'm+': _date.getMinutes(),
        's+': _date.getSeconds(),
        'q+': Math.floor((_date.getMonth() + 3) / 3),
        'S+': _date.getMilliseconds(),
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (`${_date.getFullYear()}`).substr(4 - RegExp.$1.length));
    }
    for (let k in date) {
        if (new RegExp(`(${k})`).test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : (`00${date[k]}`).substr((`${date[k]}`).length));
        }
    }
    return format;
};

// 数组contains函数
const isContain = function (arr, element) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] == element) {
            return true;
        }
    }
    return false;
};

// 定义map函数，实现间隔遍历
const intervalMap = function (arr, fn, mul = 1) {
    let a = [];
    if (mul > 0) {
        for (let i = 0; i < arr.length; i += mul) {
            let value = fn(arr[i], i);
            if (value != null) {
                a.push(value); // 如果函数fn返回null，则从数组中删除该项
            }
        }
    }
    return a;
};


/** --------- 元素工具栏功能js函数 -----------* */

function onSetting(eid, ebaseid, hpid, subCompanyId) {
    // 获取设置页面内容
    let settingUrl = `${'/page/element/setting.jsp'
        + '?eid='}${eid
         }&ebaseid=${ebaseid
         }&hpid=${hpid
         }&subcompanyid=${subCompanyId}`;
    $.post(settingUrl, null, (data) => {
        if ($.trim(data) != '') {
            $(`#setting_${eid}`).hide();
            $(`#setting_${eid}`).remove();
            $(`#content_${eid}`).prepend($.trim(data));

            $('.tabs').PortalTabs({
                getLine: 1,
                topHeight: 40,
            });
            $('.tab_box').height(0);

            $(`#setting_${eid}`).show();
            $(`#weavertabs-content-${eid}`).show();
            let urlContent = $.trim($(`#weavertabs-content-${eid}`).attr('url')).replace(/&amp;/g, '&');
            let urlStyle = $.trim($(`#weavertabs-style-${eid}`).attr('url')).replace(/&amp;/g, '&');
            let urlShare = $.trim($(`#weavertabs-share-${eid}`).attr('url')).replace(/&amp;/g, '&');
            if (urlContent != '') {
                let randomValue = new Date().getTime();

                if (ebaseid == 7 || ebaseid == 8 || ebaseid == 1 || ebaseid == 'news' || ebaseid == 29 || ebaseid == 'reportForm') {
                    $(`#setting_${eid}`).attr('randomValue', randomValue);
                }

                urlContent = `${urlContent}&random=${randomValue}`;

                $(`#weavertabs-content-${eid}`).html('');
                $(`#weavertabs-content-${eid}`).html('<img src=/images/loading2_wev8.gif> loading...');
                $(`#weavertabs-content-${eid}`).load(urlContent, {}, () => {
                    // $("#sync_datacenter_"+eid).tzCheckbox({labels:['','']});
                    $('.filetree').filetree();
                    // $(".vtip").simpletooltip();
                    // fixedPosition(eid);
                    jscolor.init();
                    // 初始化layout组件
                    initLayout();
                });
            }
            if (urlStyle != '') {
                $(`#weavertabs-style-${eid}`).load(urlStyle, {}, () => {
                    // 初始化layout组件
                    initLayout();
                    $(`#weavertabs-style-${eid}`).hide();
                });
            }
            if (urlShare != '') {
                $(`#weavertabs-share-${eid}`).load(urlShare, {}, () => {
                    $(`#weavertabs-share-${eid}`).hide();
                });
            }
        }
    });
}

// 处理hpid页面元素缓存数据
const hpinfoHandle = (param = {}, eid) => {
    let { hpinfo = {} } = param;
    let { layoutFlags = {} } = hpinfo;
    layoutFlags.map((item) => {
        if (item.areaElements.length > 0) {
            for (let i = 0; i < item.areaElements.length; i++) {
                if (item.areaElements[i].item.eid == eid) {
                    item.areaElements.splice(i, 1);
                    break;
                }
            }
        }
        return item;
    });
    return objectAssign({}, param, { hpinfo: objectAssign({}, param.hpinfo, { layoutFlags }) });
};

const getMoreRouteUrl = function (eid, ebaseid) {
    let paramsObj = window.elements_more_params[eid] || {};
    switch (ebaseid) {
        // 公告元素
        case NEWNOTICE:
            if (paramsObj.createMethod && paramsObj.createMethod == '1') {
                return `/spa/portal/moreStatic/index_more.html#/more?ebaseid=${ebaseid}&eid=${eid}&canAddNotice=${paramsObj.canAddNotice}`;
                // return '/spa/portal/moreStatic/index_more.html#/more?ebaseid=${ebaseid}&eid=${eid}&canAdd=${paramsObj.canAddNotice};
            }
            return '/spa/document/static/index.html#/main/document/more?fromwhere=jsonFilter';
        // RSS阅读器
        case RSS:
            return `/spa/portal/moreStatic/index_more.html#/more?ebaseid=${ebaseid}&eid=${eid}&tabid=${paramsObj.tabid}`;
        // 流程中心
        case WORKFLOW:
            let urger = paramsObj.urger || false;
            if (urger) {
                return '/spa/workflow/index_mobx.jsp#/main/workflow/supervise?fromwhere=jsonFilter';
            }
            return '/spa/workflow/index_mobx.jsp#/main/workflow/queryFlowResult?fromwhere=jsonFilter';
        // 集成登录
        case OUTTERSYS:
            return `/spa/portal/moreStatic/index_more.html#/more?ebaseid=${ebaseid}&eid=${eid}`;
        // 外部数据
        case OUTDATA:
            return `/spa/inte/static/index.html#/main/inte/portal/${eid}/${paramsObj.tabid}`;
        // 我的项目
        case MY_PROJECTS:
            return '/spa/prj/index.html#/main/prj/queryProjectResult';
        // 未读协作
        case UNREAD_COOPERATION:
            return '/spa/cowork/static/index.html#/main/cowork/main';
        // 通讯录
        case CONTACTS:
            return '/spa/hrm/index_mobx.html#/main/hrm/addressBook';
        // 微博
        case BLOGSTATUS:
            return '/spa/blog/index_mobx.html#/main/blog/myBlog';
        // 最新客户
        case NEW_CUSTOMERS:
            return '/spa/crm/static4report/index.html#/main/crmReport/customer/newList';
        // 建模查询中心元素
        case FORMMODECUSTOMSEARCH:
            if (paramsObj.morehref || paramsObj.morehref != '') {
                return paramsObj.morehref;
            }
            if (paramsObj.childrenColumnName && paramsObj.childrenColumnName == '1') {
                return `/spa/cube/index.html#/main/cube/search?customid=${paramsObj.customid}&displayType=treeType`;
            }
                return `/spa/cube/index.html#/main/cube/search?customid=${paramsObj.customid}`;


        // 最新会议
        case NEW_MEETING:
            return '/spa/meeting/static/index.html#/main/meeting/CalView';
        // 日程
        case DAY_PLAN:
            return '/spa/workplan/static/index.html#/main/wp/myWorkPlan';
        // 新建流程
        case ADDWF:
            return '/spa/workflow/static/index.html#/main/workflow/add';
        // 未读文档
        case UNREAD_DOCS:
            return '/spa/document/static/index.html#/main/document/more?fromwhere=jsonFilter&isNew=1';
        // 文档中心
        case NEWS:
            return '/spa/document/static/index.html#/main/document/more?fromwhere=jsonFilter';
        // 文档中心(特殊)
        case NEW_DY:
            return '/spa/document/static/index.html#/main/document/more?fromwhere=jsonFilter';
        // 我的邮件
        case MAIL:
            return '/spa/email/static/index.html#/main/email/inbox?folderid=0';
        // 公司新闻
        case LOGIN_NEWS:
            return '/spa/document/static/index.html#/main/document/more?fromwhere=jsonFilter';
        // 自定义页面元素
        case CUSTOMPAGE:
            return paramsObj.moreurl;
        // 收藏元素
        case FAVOURITE:
            return '/spa/favourite/index.html#/main/favourite/tree';
        // 日历日程
        case MYCALENDAR:
            return '/spa/workplan/static/index.html#/main/wp/myWorkPlan ';
        // 会议日历
        case MEETINGCALENDAR:
            return '/spa/meeting/static/index.html#/main/meeting/CalView';
        // 我的任务
        case MYTASK:
            return '/spa/prj/index.html#/main/prj/queryTaskResult?searchfrom=portal';
        // 排行榜元素
        case RANKINGLIST:
            return paramsObj.moreurl;
        default:
            return '';
    }
};

// 没有more页面的元素
const isNoMoreElement = (ebaseid) => {
    switch (ebaseid) {
        case WORKTASK: // 任务计划
        case IMGSLIDE: // 多图元素
        case VIDEO: // 视频元素
        case SCRATCHPAD: // 便签元素
        case WEATHER: // 天气元素
        case DATACENTER: // 个人数据
        case JOBSINFO: // 多岗位办理事项
        case AUDIO: // 音频元素
        case FLASH: // flash元素
        case CUSTOMMENU: // 自定义菜单
        case PICTURE: // 图片元素
        case REPORTFORM: // 图表元素
        case SEARCHENGINE: // 搜索元素
        case SLIDE: // 幻灯片
        case MESSAGE_REMINDING: // 消息提醒
        case MORE_NEWS: // 多新闻中心
        case MAGAZINE: // 期刊中心
        case STOCK: // 股票元素
        case DOC_CONTENT: // 文档内容
        case QUICKEENTRY: // 快捷入口
            return true;
        default:
            return false;
    }
};

//  OUTTERSYS  OUTDATA  UNREAD_COOPERATION  MY_PROJECTS  NEWNOTICE(0)  NEW_CUSTOMERS  NEW_MEETING  DAY_PLAN  ADDWF

//  ADDWF  CONTACTS  RSS  CUSTOMPAGE  WORKFLOW

const openMoreWin = function (eid, ebaseid, _moreurl, moreRouteurl) {
    if (ebaseid == 'ecodeElement') {
        let paramsObjEcode = window.elements_more_params[eid];
        const { eMoreAddress, eMoreShowType = '0' } = paramsObjEcode;
        if (eMoreShowType == '1' && eMoreAddress) {
            _moreurl = eMoreAddress;
        }
    }
    if (!_moreurl && ebaseid !== ADDWF && ebaseid !== MEETINGCALENDAR && ebaseid !== MYCALENDAR && ebaseid !== NEW_DY && ebaseid !== RANKINGLIST && ebaseid !== TIMELINE) return;
    // 没有more页面的元素
    if (isNoMoreElement(ebaseid) && !moreRouteurl) return;

    if (moreRouteurl != '') {
        openLinkUrl(moreRouteurl);
        return;
    }
    let routeurl = getMoreRouteUrl(eid, ebaseid);

    let url = routeurl || _moreurl;
    let paramsObj = window.elements_more_params[eid];
    const getTimestamp = new Date().getTime();
    if (paramsObj) {
        const { moreurl, isRouteUrl, paramsStr = '', eMoreAddress, eMoreShowType = '0' } = paramsObj;
        if (eMoreShowType == '1' && eMoreAddress) {
            url = eMoreAddress;
        } else if (moreurl !== undefined) {
            url = moreurl;
        } else if (isRouteUrl) {
                url = routeurl + paramsStr;
            } else if (_moreurl != '') {
                    url = _moreurl + paramsStr;
                }
        if (url.indexOf('?') > -1) {
            url = `${url}&timestamp=${getTimestamp}`;
        } else if (url != '') {
                url = `${url}?timestamp=${getTimestamp}`;
            }
    }
    openLinkUrl(url);
};


const _str2Int = function (s, def) {
    return isNaN(parseInt(s)) ? (isNaN(parseInt(def)) ? -1 : parseInt(def)) : parseInt(s);
};

const _s2Int = function (s) {
    return _str2Int(s, -1);
};

window.openHref = function (url) {
    if (window.doThemeAction) {
        window.doThemeAction('onLoadMain', { url });
    } else {
        window.location.href = url;
    }
};

function onShowOrHideE(eid) {
    $(`#content_${eid}`).toggle();
}

// 独立tab样式固定元素高度情况
const setContentviewHeight = function (styleheight, tabvalue) {
    let cstyle = { height: `${parseInt(styleheight) - 32}px`, overflow: 'auto' };
    switch (tabvalue) {
        // 箭头图标
        case '1':cstyle = { height: `${parseInt(styleheight) - 44}px`, overflow: 'auto' }; break;
        // 彩色箭头
        case '2':cstyle = { height: `${parseInt(styleheight) - 44}px`, overflow: 'auto' }; break;
        // 蓝灰箭头
        case '3':cstyle = { height: `${parseInt(styleheight) - 44}px`, overflow: 'auto' }; break;
        // 多彩叠层
        case '4':cstyle = { height: `${parseInt(styleheight) - 60}px`, overflow: 'auto' }; break;
        // 气泡TAB
        case '10':cstyle = { height: `${parseInt(styleheight) - 55}px`, overflow: 'auto' }; break;
        // 气泡图标TAB
        case '11':cstyle = { height: `${parseInt(styleheight) - 55}px`, overflow: 'auto' }; break;
        // 彩条图标
        case '12':cstyle = { height: `${parseInt(styleheight) - 68}px`, overflow: 'auto' }; break;
        // 便利贴1
        case '13':cstyle = { height: `${parseInt(styleheight) - 54}px`, overflow: 'auto' }; break;
        // 便利贴2
        case '14':cstyle = { height: `${parseInt(styleheight) - 69}px`, overflow: 'auto' }; break;
        // 便利贴3
        case '15':cstyle = { height: `${parseInt(styleheight) - 76}px`, overflow: 'auto' }; break;
        // 便利贴4
        case '16':cstyle = { height: `${parseInt(styleheight) - 76}px`, overflow: 'auto' }; break;
        // 点选图标样式
        case '30':cstyle = { height: `${parseInt(styleheight) - 58}px`, overflow: 'auto' }; break;
        // 标准图标样式
        case '31':cstyle = { height: `${parseInt(styleheight) - 63}px`, overflow: 'auto' }; break;
        // 滑动tab1
        case '32':cstyle = { height: `${parseInt(styleheight) - 49}px`, overflow: 'auto' }; break;
        // 滑动tab2
        case '33':cstyle = { height: `${parseInt(styleheight) - 49}px`, overflow: 'auto' }; break;
        // 胶囊tab1
        case '34':cstyle = { height: `${parseInt(styleheight) - 53}px`, overflow: 'auto' }; break;
        // 胶囊tab2
        case '35':cstyle = { height: `${parseInt(styleheight) - 53}px`, overflow: 'auto' }; break;
        // 方形tab1
        case '36':cstyle = { height: `${parseInt(styleheight) - 53}px`, overflow: 'auto' }; break;
        // 方形tab2
        case '37':cstyle = { height: `${parseInt(styleheight) - 53}px`, overflow: 'auto' }; break;
        // 对话框1
        case '38':cstyle = { height: `${parseInt(styleheight) - 63}px`, overflow: 'auto' }; break;
        // 对话框2
        case '39':cstyle = { height: `${parseInt(styleheight) - 63}px`, overflow: 'auto' }; break;

        default:cstyle = { height: `${parseInt(styleheight) - 32}px`, overflow: 'auto' };
    }
    return cstyle;
};
module.exports = {
    NoRightCom,
    handleHeight,
    doPrev,
    doNext,
    handleWidth,
    isE9Element,
    formatData,
    loadRemind,
    formatDate,
    isContain,
    intervalMap,
    onSetting,
    _s2Int,
    _str2Int,
    openMoreWin,
    openLinkUrl,
    onShowOrHideE,
    hpinfoHandle,
    isNoMoreElement,
    setContentviewHeight,
};

// 流程元素全局刷新方法
window.element_workflow_reLoad = function () {
    if (window.element_workflow_refresh && typeof window.element_workflow_refresh == 'object') {
        for (let eid in element_workflow_refresh) {
            if (typeof element_workflow_refresh[eid] == 'function') {
                element_workflow_refresh[eid]();
            }
        }
    }
};

// 文档中心元素全局刷新方法
window.element_news_reLoad = function (eid) {
    if (window.element_news_refresh && typeof window.element_news_refresh == 'object' && eid) {
        element_news_refresh[eid]();
    }
};

// 文档中心元素全局刷新方法
window.element_news_reLoad_all = function () {
    if (window.element_news_refresh && typeof window.element_news_refresh == 'object') {
        for (let eid in element_news_refresh) {
            if (typeof element_news_refresh[eid] == 'function') {
                element_news_refresh[eid]();
            }
        }
    }
};


// 未读文档元素全局刷新方法
window.element_unReadDoc_reLoad = function (eid) {
    if (window.element_unReadDoc_refresh && typeof window.element_unReadDoc_refresh == 'object') {
        element_unReadDoc_refresh[eid]();
    }
};

// 未读文档元素全局刷新方法
window.element_unReadDoc_reLoad_all = function () {
    if (window.element_unReadDoc_refresh && typeof window.element_unReadDoc_refresh == 'object') {
        for (let eid in element_unReadDoc_refresh) {
            if (typeof element_unReadDoc_refresh[eid] == 'function') {
                element_unReadDoc_refresh[eid]();
            }
        }
    }
};

// 未读协作元素全局刷新方法
window.element_cooperation_reLoad = function (eid) {
    if (window.element_cooperation_refresh && typeof window.element_cooperation_refresh == 'object') {
        element_cooperation_refresh[eid]();
    }
};

// 未读协作元素全局刷新方法
window.element_cooperation_reLoad_all = function () {
    if (window.element_cooperation_refresh && typeof window.element_cooperation_refresh == 'object') {
        for (let eid in element_cooperation_refresh) {
            if (typeof element_cooperation_refresh[eid] == 'function') {
                element_cooperation_refresh[eid]();
            }
        }
    }
};

// 我的邮件元素全局刷新方法
window.element_mail_reLoad = function (eid) {
    if (window.element_mail_refresh && typeof window.element_mail_refresh == 'object') {
        element_mail_refresh[eid]();
    }
};

// 我的邮件元素全局刷新方法
window.element_mail_reLoad_all = function () {
    if (window.element_mail_refresh && typeof window.element_mail_refresh == 'object') {
        for (let eid in element_mail_refresh) {
            if (typeof element_mail_refresh[eid] == 'function') {
                element_mail_refresh[eid]();
            }
        }
    }
};

